cmake_minimum_required(VERSION 3.0)
project(study VERSION 1.0)
SET(PROJECT_VERSION 1.2.3.4)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin)

find_package(Git)
EXECUTE_PROCESS(COMMAND git describe --tags
        TIMEOUT 10
        OUTPUT_VARIABLE GIT_VERSION
        OUTPUT_STRIP_TRAILING_WHITESPACE
        )
MESSAGE(STATUS "building from git tag ${GIT_VERSION}")
MESSAGE(STATUS "project version ${PROJECT_VERSION}")
add_definitions(-DBUILD_VERSION=\"${GIT_VERSION}\")
add_definitions(-DAPP_VERSION=\"${PROJECT_VERSION}\")


execute_process(COMMAND ${GIT_EXECUTABLE} describe --abbrev=6 --dirty --always --tags
                WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
                OUTPUT_VARIABLE GIT_REPO_VERSION
                OUTPUT_STRIP_TRAILING_WHITESPACE)#获取最新 commit 日期，YYYY-MM-DD
execute_process(COMMAND ${GIT_EXECUTABLE} log -1 --format=%cd --date=short
                WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
                OUTPUT_VARIABLE GIT_REPO_DATE
                OUTPUT_STRIP_TRAILING_WHITESPACE)# 获取最新 commit Hash
execute_process(COMMAND ${GIT_EXECUTABLE} log -1 --format=%H
                WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
                OUTPUT_VARIABLE GIT_REPO_HASH
                OUTPUT_STRIP_TRAILING_WHITESPACE)# 写入头文件宏定义的版本字符串，日期和 Hash
file(WRITE ${PROJECT_BINARY_DIR}/auto_version.h
     "#define REPO_VERSION \"${GIT_REPO_VERSION}\"\n#define REPO_DATE \"${GIT_REPO_DATE}\"\n#define REPO_HASH \"${GIT_REPO_HASH}\"\n")# 包含引用目录，源文件可以直接用 #include "repo_version.h" 包含

add_executable(${PROJECT_NAME} main.cpp ${PROJECT_BINARY_DIR}/auto_version.h)
